package com.qiguliuxing.dts.merchant.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.type.AdminTypeEnum;
import com.qiguliuxing.dts.common.util.RegexUtils;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.common.util.bcrypt.BCryptPasswordEncoder;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsAdmin;
import com.qiguliuxing.dts.merchant.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.merchant.service.MerchantAdminService;
import com.qiguliuxing.dts.merchant.support.AuthSupport;
import com.qiguliuxing.dts.merchant.support.MerchantResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.qiguliuxing.dts.merchant.support.MerchantResponseCode.*;

/**
 * 商户管理员接口
 *
 * @author qiguliuxing
 * @since 1.0.0
 */
@RestController
@RequestMapping("/merchant/admin")
@Validated
@Api(tags = ApiAdminConsts.Admin.PARENT)
public class MerchantAdminController {
    private static final Logger logger = LoggerFactory.getLogger(MerchantAdminController.class);

    @Autowired
    private MerchantAdminService merchantAdminService;

    @GetMapping("/list")
    @RequiresPermissions("merchant:admin:list")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "查询")
    @ApiOperation(value = ApiAdminConsts.Admin.LIST)
    @WebLog(description = ApiAdminConsts.Admin.LIST, excludes = {LogParamsConsts.RESPONSE})
    public Object list(@ApiParam(value = "用户名称") String username,
                       @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
                       @ApiParam(value = "分页大小", defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
                       @ApiParam(value = "排序字段", defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @ApiParam(value = "排序规则", defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
        List<DtsAdmin> adminList = merchantAdminService.querySelective(AuthSupport.merchantBrandId(), username, page, limit, sort, order);
        long total = PageInfo.of(adminList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", adminList);
        return ResponseUtils.ok(data);
    }

    private Object validate(DtsAdmin admin) {
        String name = admin.getUsername();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtils.badArgument();
        }
        if (!RegexUtils.isUsername(name)) {
            logger.error("校验错误：{}", ADMIN_INVALID_NAME.desc());
            return MerchantResponseUtils.fail(ADMIN_INVALID_NAME);
        }
        String password = admin.getPassword();
        if (StringUtils.isEmpty(password) || password.length() < 6) {
            logger.error("校验错误：{}", ADMIN_INVALID_PASSWORD.desc());
            return MerchantResponseUtils.fail(ADMIN_INVALID_PASSWORD);
        }
        String mail = admin.getMail();
        if (StringUtils.isEmpty(mail)) {
            logger.error("校验错误：{}", ADMIN_INVALID_MAIL.desc());
            return MerchantResponseUtils.fail(ADMIN_INVALID_MAIL);
        }
        String tel = admin.getTel();
        if (!RegexUtils.isMobileExact(tel)) {
            logger.error("校验错误:{}", ADMIN_INVALID_MOBILE.desc());
            return MerchantResponseUtils.fail(ADMIN_INVALID_MOBILE);
        }
        return null;
    }

    @PostMapping("/create")
    @RequiresPermissions("merchant:admin:create")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "添加")
    @ApiOperation(value = ApiAdminConsts.Admin.CREATE)
    @WebLog(description = ApiAdminConsts.Admin.CREATE, persistence = true)
    public Object create(@RequestBody DtsAdmin admin) {
        Object error = validate(admin);
        if (error != null) {
            return error;
        }

        String username = admin.getUsername();
        List<DtsAdmin> adminList = merchantAdminService.findMerchantAdmin(username);
        if (adminList.size() > 0) {
            logger.error("系统管理->管理员管理->添加 ,错误：{}", ADMIN_NAME_EXIST.desc());
            return MerchantResponseUtils.fail(ADMIN_NAME_EXIST);
        }

        String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        admin.setPassword(encodedPassword);

        // 创建的新用户必须是商户类型，且与当前用户归属同一个商户
        admin.setType(AdminTypeEnum.MERCHANT.getType());
        admin.setBrandId(AuthSupport.merchantBrandId());
        merchantAdminService.add(admin);

        return ResponseUtils.ok(admin);
    }

    @GetMapping("/read")
    @RequiresPermissions("merchant:admin:read")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "详情")
    @ApiOperation(value = ApiAdminConsts.Admin.READ)
    @WebLog(description = ApiAdminConsts.Admin.READ)
    public Object read(@ApiParam(value = "管理员id") @NotNull Integer id) {
        DtsAdmin admin = merchantAdminService.findById(id);
        return ResponseUtils.ok(admin);
    }

    @PostMapping("/update")
    @RequiresPermissions("merchant:admin:update")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "编辑")
    @ApiOperation(value = ApiAdminConsts.Admin.UPDATE)
    @WebLog(description = ApiAdminConsts.Admin.UPDATE, persistence = true)
    public Object update(@RequestBody DtsAdmin admin) {
        Object error = validate(admin);
        if (error != null) {
            return error;
        }

        Integer anotherAdminId = admin.getId();
        if (anotherAdminId == null) {
            return ResponseUtils.badArgument();
        }

        String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        admin.setPassword(encodedPassword);

        if (merchantAdminService.updateById(admin) == 0) {
            logger.error("系统管理->管理员管理-编辑 ,错误：{}", "更新数据失败！");
            return ResponseUtils.updatedDataFailed();
        }

        return ResponseUtils.ok(admin);
    }

    @PostMapping("/delete")
    @RequiresPermissions("merchant:admin:delete")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "删除")
    @ApiOperation(value = ApiAdminConsts.Admin.DELETE)
    @WebLog(description = ApiAdminConsts.Admin.DELETE, persistence = true)
    public Object delete(@RequestBody DtsAdmin admin) {
        Integer anotherAdminId = admin.getId();
        if (anotherAdminId == null) {
            return ResponseUtils.badArgument();
        }

        merchantAdminService.deleteById(anotherAdminId);
        return ResponseUtils.ok();
    }
}
